# coding:utf-8
import StringIO
import json
import datetime
import random
from web.utils import helper
from flask import Blueprint, render_template, request, session, make_response, redirect, url_for, g, \
    render_template_string
from ..utils.permissions import require_user, require_visitor
from ..utils.uploadsets import images, random_filename, process_question, avatars
from web.forms import SigninForm, RegisterForm, PayForm
from web.models import User, MsgRecord, db
from web.models.product import TouguProduct, ModalType, Product, Zhuzibao,TouguProductData
from web.utils.account import signout_user, signin_user
from web.utils.code2 import getCodePiture
from web.utils.sendmsg import send_short_msg
from sqlalchemy import text

bp = Blueprint('site', __name__)


@bp.route('/', methods=['GET'])
def index():
    form = SigninForm()
    return render_template('site/index.html', form=form)


@bp.route('/tougu', methods=['GET'])
def tougu():
    modal_types = ModalType.query.all()

    return render_template('site/tougu.html', modal_types=modal_types)


@bp.route('/module', methods=['GET'])
def module():
    id = int(request.args.get("id", 0))
    product = TouguProduct.query.get(id)
    info = TouguProductData.query.filter(TouguProductData.product_id ==id,text("week(create_time)=week(now())")).first()
    info.max_return=float(info.max_return)*100
    info.win_odds=float(info.win_odds)*100
    info.year_income=float(info.year_income)*100
    #info.online_time=time.strftime('%Y年%m月%d日 ',info.online_time)
    return render_template('site/module.html', product=product,info=info)


@bp.route('/product', methods=['GET'])
def product():
    products = Product.query.all()
    return render_template('site/product.html', products=products)


@bp.route('/partner', methods=['GET'])
def partner():
    return render_template('site/partner.html')


@bp.route('/zhuzibao', methods=['GET'])
def zhuzhibao():
    form = PayForm()
    info=Zhuzibao.query.first()
    return render_template('site/zhuzhibao.html', form=form,info=info)


@bp.route('/aboutus', methods=['GET'])
def aboutus():
    return render_template('site/aboutus.html')


@bp.route('/login', methods=['GET', 'POST'])
def login():
    form = SigninForm()
    status = ""
    login_error = 0
    if g.user:
        return redirect("admin/home")
    if request.method == 'POST':
        if form.is_submitted():
            user = User.query.filter(User.name == form.username.data).first()
            if user.check_password(form.password.data):
                signin_user(user)
                return redirect("user/home")
            else:
                login_error = 1
        else:
            status = "登录失败"
    return render_template("site/login.html", form=form, status=status, login_error=login_error)


@bp.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm()
    if request.method == 'POST':
        name = form.name.data.replace(' ', '')
        email = form.email.data
        mobile = form.mobile.data
        password = form.password.data
        code = form.code.data
        user = User(name=name, mobile=mobile, email=email, password=password, is_active=True)
        user.hash_password()
        user.gene_token()
        db.session.add(user)
        db.session.commit()
        signin_user(user)
        return redirect(url_for('user.home'))

    return render_template('site/register.html', form=form)


@bp.route('/logout')
def loginout():
    """登出"""
    signout_user()
    return redirect(url_for('site.login'))


@bp.route('/upload_image', methods=['POST'])
@require_user
def upload_image():
    try:
        filename = process_question(request.files['file'], images)
    except Exception, e:
        return json.dumps({'status': 'no', 'error': e.__repr__()})
    else:
        return (json.dumps({"status": 'ok', "msg": "", "base_url": "", "name": filename}))


@bp.route('/verifyCode', methods=['GET'], defaults={"code": None})
@bp.route('/verifyCode/<string:code>', methods=['GET'])
def get_code(code):
    # 把strs发给前端,或者在后台使用session保存
    mstream = StringIO.StringIO()
    # validate_code = create_validate_code()
    validate_code = getCodePiture()
    img = validate_code[0]
    img.save(mstream, "GIF")
    session['validate'] = validate_code[1]
    print session['validate']
    # return (mstream.getvalue(), "image/gif")
    response = make_response(mstream.getvalue())
    response.headers['Content-Type'] = 'image/gif'
    return response


@bp.route('/sendcode', methods=['GET', 'POST'])
def sendcode():
    print request.json
    mobile_number = request.args.get("mobile")
    msg_code = random.randint(100000, 999999)
    session['msg_code'] = str(msg_code)
    # print session.get('msg_code')
    ip = request.remote_addr
    last_request_time = datetime.datetime.now() - datetime.timedelta(minutes=1)
    # 查找一分钟内的register 验证码请求记录

    record = MsgRecord.query.filter(MsgRecord.type == 'register', MsgRecord.ip == ip,
                                    MsgRecord.time >= last_request_time)
    permit = False if record.count() > 0 else True
    if permit:
        tpl_value = "#code#=%s" % (str(msg_code))
        print tpl_value
        # 调用短信模板1141781
        send_short_msg('1141781', tpl_value, mobile_number)
        new_record = MsgRecord(time=datetime.datetime.now(), type="register", ip=ip)
        # 写入请求记录表
        db.session.add(new_record)
        db.session.commit()
        return (json.dumps({"msg": 'ok', "error": ''}))
    else:
        return (json.dumps({"msg": '请勿频繁请求', "error": 'error'}))


from lxml import etree
import time


def CDATA(text=None):
    element = etree.Element(CDATA)
    element.text = text
    return element


@bp.route('/data_module', methods=['GET', 'POST'])
def data_module():
    """参考http://www.zlw.com/module.asp?id=187"""
    id = int(request.args.get("id", 0))
    v = int(request.args.get("v", 0))
    v1 = request.args.get("v1", "2015-05-05")
    v2 = request.args.get("v2", "2015-11-30")
    if v==1:#一个月
        infos = TouguProductData.query.filter(TouguProductData.product_id ==id,
                                              text("DATE_SUB(CURDATE(),INTERVAL 1 MONTH) <= date(online_time)")).order_by('online_time').all()
        v2 = time.strftime("%Y-%m-%d", time.localtime())
        v1=helper.get_today_month(-1)
    elif v==2:#三个月
        infos = TouguProductData.query.filter(TouguProductData.product_id ==id,
                                              text("DATE_SUB(CURDATE(),INTERVAL 3 MONTH) <= date(online_time)")).order_by('online_time').all()
        v2 = time.strftime("%Y-%m-%d", time.localtime())
        v1=helper.get_today_month(-3)
    elif v==3:#半年
        infos = TouguProductData.query.filter(TouguProductData.product_id ==id,
                                              text("DATE_SUB(CURDATE(),INTERVAL 6 MONTH) <= date(online_time)")).order_by('online_time').all()
        v2 = time.strftime("%Y-%m-%d", time.localtime())
        v1=helper.get_today_month(-6)
    elif v==4:#一年
        infos = TouguProductData.query.filter(TouguProductData.product_id ==id,
                                              text("DATE_SUB(CURDATE(),INTERVAL 1 YEAR) <= date(online_time)")).order_by('online_time').all()
        v2 = time.strftime("%Y-%m-%d", time.localtime())
        v1=helper.get_today_month(-12)
    elif v==5:#所有
        v2 = time.strftime("%Y-%m-%d", time.localtime())
        v1 ="2010-01-01"
        infos = TouguProductData.query.filter(TouguProductData.product_id ==id).order_by('online_time').all()
    elif ((v1 == "") and (v2 == "")):
        v2 = time.strftime("%Y-%m-%d", time.localtime())
        v1 ="2010-01-01"
        infos = TouguProductData.query.filter(TouguProductData.product_id ==id).order_by('online_time').all()
    else:
         infos = TouguProductData.query.filter(TouguProductData.product_id ==id,
                                              TouguProductData.online_time<=datetime.datetime.strptime(v2,'%Y-%m-%d'),
                                              TouguProductData.online_time>=datetime.datetime.strptime(v1,'%Y-%m-%d')).order_by('online_time').all()
    root = etree.Element("root")
    r_string='['
    if len(infos)>0:
     r_string+='['+str(long(time.mktime(infos[0].online_time.timetuple())*1000))+','+infos[0].week_income+']'
    for i in range(1,len(infos)):
        r_string+=',['+str(long(time.mktime(infos[i].online_time.timetuple())*1000))+','+infos[i].week_income+']'
    r_string+=']'
    r = etree.SubElement(root, "r")
    r.text = r_string
    r1 = etree.SubElement(root, "r1")
    r1.text = v1
    r2 = etree.SubElement(root, "r2")
    r2.text = v2
    sitemap_xml = render_template_string(etree.tostring(root, pretty_print=True))
    response = make_response(sitemap_xml)
    response.headers["Content-Type"] = "application/xml"
    return response
